package com.cares.core.mng.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.cares.core.base.service.BaseService;
import com.cares.core.mng.repository.OrgnizationMapper;
import com.cares.core.utils.Constant;
import com.cares.entity.mng.Orgnization;

/**
 * 
 * @author zhiweip
 */
@Service("orgService")
@Transactional(readOnly = true)
public class OrgService extends BaseService {

	private static Logger logger = LoggerFactory.getLogger(OrgService.class);

	@Autowired
	private OrgnizationMapper orgDao;

	/**
	 * 先访问Memcached, 使用JSON字符串存放对象以节约空间.
	 */
	public Orgnization get(Long id) {
		if (null == id)
			return null;
		Orgnization org = orgDao.get(id);
		if (null != org && org.getUpOrgId().intValue() != 0) {
			org.setUpOrgnization(orgDao.get(org.getUpOrgId()));
		}
		return org;
	}

	/**
	 * 先访问Memcached, 使用JSON字符串存放对象以节约空间.
	 */
	public Orgnization get(String orgCode) {
		return get(orgCode, false);
	}

	public Orgnization get(String orgCode, boolean all) {
		if (null == orgCode)
			return null;
		Orgnization org = orgDao.findByCode(orgCode);
		if (all)
			if (null != org && org.getUpOrgId().intValue() != 0) {
				org.setUpOrgnization(orgDao.get(org.getUpOrgId()));
			}
		return org;
	}

	public List<Orgnization> searchOrg(Orgnization org) {
		return orgDao.find(org);
	}

	public boolean checkComp(String orgCode) {
		/*
		 * List air = airCompanyService.searchCompany(orgCode, null); if (null
		 * != air && air.size() > 0) { return false; } List agent =
		 * airAgentService.searchAgent(orgCode); if (null != agent &&
		 * agent.size() > 0) { return false; }
		 */
		return true;
	}

	public void updateOrg(Orgnization org) {
		Assert.notNull(org.getId(), "缺少主键");
		
		Orgnization orgDB = orgDao.get(org.getId());
		if (orgDB.getUpOrgId().intValue() != org.getUpOrgId().intValue()) {
			org.setOrgPath(getOrgPath(org.getUpOrgId()) + org.getId() + ">>");
			Map<String,String> map=new HashMap<String, String>();
			map.put("oldPath", orgDB.getOrgPath());
			map.put("newPath", org.getOrgPath());
			orgDao.updateSubOrgPath(map);
		}

		if (org.getId().intValue() == 1) {
			org.setUpOrgId(new Long(0));
		}
		if (org.getId().intValue() < 6) {
			org.setOrgCode(null);
			org.setUpOrgId(null);
			org.setOrgPath(null);
		}
		org.setUpdateUser(super.getCurrentUserName());
		org.setUpdateTime(new Date());
		orgDao.update(org);
	}

	private Orgnization insertOrg(Orgnization org) {
		org.setCreateUser(super.getCurrentUserName());
		org.setCreateTime(new Date());
		orgDao.save(org);
		
		org.setOrgPath(getOrgPath(org.getUpOrgId()) + org.getId() + ">>");
		orgDao.update(org);
		return org;
	}

	public void deleteOrg(Long id) {
		orgDao.delete(id);
	}
	
	/**
	 * 机构维护：
	 * 1、添加航空公司办事处：从代理人系统获取航空公司信息
	 * @param org
	 * @return
	 */
	@Transactional(readOnly = false)
	public synchronized int saveOrUpdateOrg(Orgnization org) {
		if (null == org.getUpOrgId())
			org.setUpOrgId(new Long(1));

		Assert.notNull(org.getOrgCode(), ">>ERROR: OrgCode TYPE IS NULL!");
		Assert.notNull(org.getOrgType(), ">>ERROR: ORG TYPE IS NULL!");
		if(null!=org.getId()&& org.getId().intValue()==org.getUpOrgId().intValue())
			return 2;
		
		Orgnization param = new Orgnization();
		param.setOrgCode(org.getOrgCode());
		List<Orgnization> check = searchOrg(param);

		if (null != check && check.size() > 0) {
			if (org.getId() == null)
				return 2;
			else if (check.get(0).getId().intValue() != org.getId().intValue()) {
				return 2;
			}
		}

		if (null != org.getId()) {
			updateOrg(org);
		} else {
			insertOrg(org);
		}
		return 1;
	}

	public List orgTree(Long nodeId) {
		return orgTree(nodeId, 0);
	}

	public List orgTree(Long nodeId, int style) {
		List<Map<String, Object>> itemsList = new ArrayList<Map<String, Object>>();

		/*
		 * if (Constan.ORG_NODE_ARI_COMPANY.intValue() == nodeId.intValue()) {//
		 * 航空公司 List<AirCompany> list = airCompanyService.searchCompany(null,
		 * null); if (null != list) for (AirCompany air : list) { Map<String,
		 * Object> item = new HashMap<String, Object>(); item.put("id",
		 * air.getAirCode()); item.put("text", "[" + air.getAirCode() + "]" +
		 * air.getName_zh()); item.put("nameCn", air.getName_zh());
		 * item.put("nameEn", air.getName_en()); item.put("orgCode",
		 * air.getAirCode()); item.put("orgType", Constan.ORG_TYPE_ARI_COMPANY);
		 * item.put("iconCls", "icon-flight"); item.put("state", "open");
		 * itemsList.add(item); } } else {// 代理人 // FIXME 安全验证：访问的机构是否合法
		 * Orgnization nodeOrg = this.get(nodeId); if
		 * (Constan.ORG_TYPE_AGENTCOMP.equals(nodeOrg.getOrgType())) {// 从***获取
		 * // 代理人 List<AirAgent> list = airAgentService.searchAgent(null,
		 * null);//nodeOrg.getOrgCode() if (null != list) { for (AirAgent air :
		 * list) { makeNode(itemsList, air); } } } else {
		 */
		// 系统中的机构
		// 代理人公司
		List<Orgnization> menuList = getSubOrgObject(nodeId, style);

		for (Orgnization org : menuList) {
			makeNode(nodeId, itemsList, org);
		}

		/*
		 * } }
		 */
		return itemsList;
	}

	public void makeNode(Long nodeId, List<Map<String, Object>> itemsList,
			Orgnization org) {
		Map<String, Object> item = new HashMap<String, Object>();
		item.put("id", org.getId());
		item.put("text", "[" + org.getOrgCode() + "]" + org.getNameCn());
		item.put("nameCn", org.getNameCn());
		item.put("nameEn", org.getNameEn());
		item.put("orgCode", org.getOrgCode());
		item.put("orgType", org.getOrgType());
		item.put("orgTypeDesc", org.getOrgType());
		item.put("airCode", org.getAirCode());
		if (Constant.IS_N.equals(org.getOrgState())) {// 无效机构
			item.put("iconCls", "icon-red-ball");
		} else if (Constant.ORG_TYPE_DEPARTMENT.equals(org.getOrgType())) {// 部门
			item.put("iconCls", "menu-oprateMgr");
		} else {
			item.put("iconCls", "icon-blue-ball");
		}

		if (nodeId.intValue() < 4) {
			item.put("state", "closed");
		} else if (hasSubOrgObject(org.getId())) {
			item.put("state", "closed");
		} else {
			item.put("state", "open");
		}
		// item.put("children", getSubOrgObject(menu.getId(),
		// style));
		itemsList.add(item);
	}

	private List<Orgnization> getSubOrgObject(Long upMenuId, int style) {
		Orgnization org = new Orgnization();
		org.setUpOrgId(upMenuId);
		return orgDao.find(org);
	}

	private boolean hasSubOrgObject(Long upMenuId) {
		Orgnization org = new Orgnization();
		org.setUpOrgId(upMenuId);
		Integer count = orgDao.countBy(org);
		if (count.intValue() > 0) {
			return true;
		}
		return false;
	}

	/**
	 * 路径
	 * 
	 * @param orgId
	 * @return
	 */
	public String getOrgPath(Long orgId) {
		Orgnization param = orgDao.get(orgId);
		if (param == null) {
			return "1>>";
		} else if (param.getUpOrgId().intValue() == 0) {
			return param.getId() + ">>";
		} else {
			return getOrgPath(param.getUpOrgId()) + param.getId() + ">>";
		}

	}
	
	/**
	 * 返回当前用户所属的org以及其子org
	 * @return
	 */
	public List<Orgnization> getAllSubOrg(){
		return orgDao.findByPath(super.getCurrentUser().getOrgPath());
	}
}
